<template>
  <div class="login-box-wrapper">
    <div class="content">
      <div></div>
      <div>
        <el-form ref="formComponents" :model="formData" label-position="right" :rules="dataRule"
          @submit.prevent="onSubmit">
          <p>通用管理系统</p>
          <el-form-item prop="account">
            <el-input v-model="formData.account" placeholder="请输入账号" :prefix-icon="Avatar" />
          </el-form-item>
          <el-form-item prop="password">
            <el-input type="password" v-model="formData.password" placeholder="请输入密码" :prefix-icon="Key" />
          </el-form-item>
          <el-form-item prop="captcha" style="position: relative;">
            <el-input v-model="formData.captcha" placeholder="验证码" clearable></el-input>
            <div style="position: absolute;right: 5px;top: 5px;">
              <img :src="captchaPath" @click="getCaptcha()" style="width: 140px;height: 40px;cursor: pointer;" />
            </div>
          </el-form-item>
          <el-button type="primary" native-type="submit">立即登录
          </el-button>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { getUUID } from "@/tools";
import { setupDynamicRouter } from '@/router';
import { Avatar, Key } from "@element-plus/icons-vue";
import { useSystemInfo } from "@/store/pinia-store";
import { ElForm, ElMessage, FormRules } from "element-plus";
import { computed, onMounted, reactive, ref, unref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { HandleLogin, LoginFormInfo } from '@/api';
const envObj = import.meta.env

// 使用系统状态信息
const systemInfo = useSystemInfo(),
  // 表单校验规则
  dataRule = reactive<FormRules>({
    account: [{ required: true, message: "帐号不能为空", trigger: "blur" }],
    password: [
      { required: true, message: "密码不能为空", trigger: "blur" },
    ],
    captcha: [
      { required: true, message: "验证码不能为空", trigger: "blur" }
    ],
  }),
  // 相应对象
  formData = reactive<LoginFormInfo>({
    account: "",
    password: "",
    captcha: "",
    uuid: ""
  }),
  // 验证码地址计算属性
  captchaPath = computed(() => {
    if (!formData.uuid) {
      return '';
    }
    return `${envObj.VITE_API_BASE}/sysCaptcha/captcha.jpg?uuid=${formData.uuid}`;
  }), route = useRoute(), router = useRouter(),
  // 登录可能存在的重定向目标地址
  redirectPath = computed<string>(() => {
    return route.query.redirect as string || "";
  }),
  // 表单组件引用对象
  formComponents = ref<InstanceType<typeof ElForm>>();
// 重置验证码
function getCaptcha(id?: string) {
  formData.uuid = id || getUUID();
}
onMounted(() => {
  getCaptcha();
});
/**
 * 登录函数
 */
async function onSubmit() {
  await unref(formComponents)!.validate();
  try {
    // 登录第一步,拿到token
    let { token } = await HandleLogin(formData);
    // 写缓存
    sessionStorage.setItem("token", token);
    console.log(Date.now(), "获取token成功");
    //  初始化全局状态管理中用户信息
    await systemInfo.getUserInfo();
    console.log(Date.now(), "用户信息初始化完成");
    // 写入动态路由
    const { originalMenuList } = await setupDynamicRouter(systemInfo.currentActiveApplication, router);
    // 更新菜单信息
    systemInfo.updateMenuList(originalMenuList);
    const redi = unref(redirectPath)
    // 跳转main框架页,由框架页处理后续页面跳转逻辑
    router.replace({ name: "main", query: redi ? { redirectPath: redi } : {} });
  } catch (e) {
    // 登录任何环节失败后,更新验证码,并清除缓存信息
    getCaptcha();
    localStorage.clear();
    sessionStorage.clear();
    console.error(e);
    ElMessage.error(e as string);
  }
}

</script>

<style lang="less">
/*登录框样式*/
.login-box-wrapper {
  padding: 20vh 0;
  box-sizing: border-box;
  height: 100%;
  background-image: url("@/assets/img/20220314112454.png");
  background-size: cover;
  background-repeat: no-repeat;

  .content {
    width: 800px;
    height: 460px;
    border-radius: 10px;
    box-shadow: 0 0 20px #dbdbdb;
    background-color: white;
    margin: 0 auto;
    display: flex;
    justify-content: space-between;

    >div {
      width: 50%;
    }

    >div:first-child {
      border-radius: 10px 0 0 10px;
      background-position-x: -40px;
      background-image: url("@/assets/img/20220314112425.png");
      background-size: cover;
      background-repeat: no-repeat;
    }

    form {
      width: 100%;
      height: 300px;
      padding: 0 40px;
      margin-top: 50px;
      box-sizing: border-box;

      // 从全局样式表中移过来的
      .el-input__inner {
        height: 50px;
        line-height: 50px;
        border: none;
        outline: none;
        border-radius: 0;
      }

      p {
        line-height: 30px;
        letter-spacing: 3px;
        text-align: center;
        font-size: 26px;
        color: #1482f0;
      }

      /*按钮大小*/

      .el-button {
        width: 100%;
        height: 50px;
        border-radius: 0;
        margin-top: 10px;
        border: none;
        background-image: linear-gradient(to right, #68adff, #1a5dc5);
      }
    }
  }
}
</style>
